package com.heima.admin.gateway.filter;

import com.heima.admin.gateway.util.AppJwtUtil;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * 自定义拦截器
 */
@Component
@Slf4j
public class AuthorizeFilter implements GlobalFilter , Ordered {
    /**
     * 编写网关过滤逻辑
     * @param exchange
     * @param chain
     * @return
     */
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        log.info("【拦截器】 --- begin");
        //获取request 和 response
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();

        //判断是否登录,放行登录
        if (request.getURI().getPath().contains("/login")){
            log.info("【登录放行】");
            return chain.filter(exchange);
        }

        //尝试获取token
        try {
            String token = request.getHeaders().getFirst("token");
            log.info("【获取token】:{}",token);
            if(StringUtils.isBlank(token)){ //token为空
                response.setStatusCode(HttpStatus.UNAUTHORIZED);
                return response.setComplete();
            }
            //检验token是否有效
            Claims claims = AppJwtUtil.getClaimsBody(token);
            int verifiedToken = AppJwtUtil.verifyToken(claims);
            if(verifiedToken == 1 || verifiedToken == 2){
                //无效
                response.setStatusCode(HttpStatus.UNAUTHORIZED);
                return response.setComplete();
            }
            //获取用户id
            Object userId = claims.get("id");
            //获取用户信息存入header中
            log.info("【获取用户id:{}】",userId);
            ServerHttpRequest serverHttpRequest = request.mutate().header("userId", userId.toString()).build();
            //重置请求
            exchange.mutate().request(serverHttpRequest);
        }catch (Exception e){
            e.printStackTrace();
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            log.error("【解析token出错】");
            return response.setComplete();
        }
        log.info("【放行】--- end");
        return chain.filter(exchange);
    }

    /**
     * 过滤优先级
     * @return
     */
    @Override
    public int getOrder() {
        return 0;
    }
}
